//
//  HNSH_AccountEditViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/28.
//

#import "HNSH_AccountEditViewController.h"

//view
#import "HNSH_AccountCell.h"
#import "HNSH_AccountEditHeaderView.h"

#import "HNSH_UploadLocalAlert.h"

//toor
#import "HNSH_AuthTool.h"

//vc
#import "HNSH_ChangeNameViewController.h"           //修改昵称
//#import "HNSH_RealNameAuthViewController.h"         //实名认证

@interface HNSH_AccountEditViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
/* infoAry */
@property (nonatomic, strong) NSArray *infoAry;

/* headerView */
@property (nonatomic, strong) HNSH_AccountEditHeaderView *headerView;

/* headerUrl */
@property (nonatomic, copy) NSString *headerUrl;

/* addBtn */
@property (nonatomic, strong) UIButton *addBtn;
@end

static NSString *HNSH_AccountCellID = @"HNSH_AccountCellID";

@implementation HNSH_AccountEditViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.headerView) {
        self.headerView.userInfo = [ST_UserManager shareInstance].user;
    }
    [self reloadInfoAry];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self showNavTitle:@"账户管理" showLeftItem:YES];
    
    self.view.backgroundColor = [UIColor appWhiteLabelColor];
    
    [self configTableView];
    
    [self.view addSubview:self.addBtn];
}

- (void)configTableView {
    self.tableView.rowHeight = 44;
    [self.tableView registerClass:[HNSH_AccountCell class] forCellReuseIdentifier:HNSH_AccountCellID];
    
    HNSH_AccountEditHeaderView *view = [[HNSH_AccountEditHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 260)];
    WeakSelf(weakSelf);
    view.headerBlock = ^{
        [weakSelf chooseImage];
    };
    self.headerView = view;
    self.tableView.tableHeaderView = view;
}

//MARK: 保存修改
- (void)save{
    if (![self.headerUrl isNotBlank]) {
        [self.view makeToast:@"请选择头像"];
        return;
    }
    NSDictionary * params = @{@"avatar_url":self.headerUrl};
    [HNSH_UserNetServer requestUserUpdateWithParams:params success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"保存成功"];
            [ST_UserManager shareInstance].user.avatar_url = self.headerUrl;
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark lazy
- (NSArray *)infoAry {
    if (!_infoAry) {
        _infoAry = @[@{@"title":@"昵称",@"des":@""},
                     @{@"title":@"实名认证",@"des":@""},
                     @{@"title":@"我的区域",@"des":[ST_UserManager shareInstance].user.location}
        ];
    }
    return _infoAry;
}

- (UIButton *)addBtn{
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addBtn.frame = CGRectMake(30, kScreenHeight - 50 - 23 - kBottomSafeHeight, kScreenWidth - 60, 50);
        [_addBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_addBtn setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _addBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        _addBtn.backgroundColor = [UIColor appGreenColor];
        _addBtn.layer.cornerRadius = 25;
        _addBtn.layer.masksToBounds = YES;
        [_addBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

//MARK: 修改头像
- (void)chooseImage{
    UIAlertController * alertSheet = [UIAlertController alertControllerWithTitle:@"修改头像" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HNSH_AuthTool requestCameragraph:^(BOOL isAuth) {
            if (isAuth) {
                [self startChooseImage:UIImagePickerControllerSourceTypeCamera];
            } else {
                [self.view makeToast:@"未获得权限，无法上传图片"];
            }
        }];
    }]];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HNSH_AuthTool requestForPhotoAuth:^(BOOL isAuth) {
            if (isAuth) {
                [self startChooseImage:UIImagePickerControllerSourceTypePhotoLibrary];
            } else {
                [self.view makeToast:@"未获得权限，无法上传图片"];
            }
        }];
    }]];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertSheet animated:YES completion:nil];
}

- (void)startChooseImage:(UIImagePickerControllerSourceType)sourceType{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.allowsEditing = YES;
    imagePicker.delegate = self;
    imagePicker.sourceType = sourceType;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSData * data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerEditedImage], 0.5);
        if (!data) {
            data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.5);
        }
        [self commitImgToAliyunOSS:data];
    }];
}


//MARK: 上传图片到七牛
- (void)commitImgToAliyunOSS:(NSData *)imgData{
    UIImage * image = [UIImage imageWithData:imgData];
    [ST_BaseNetManager uploadImageWithImageData:image progress:^(NSString *key, float percent) {
        
    } complate:^(NSString * _Nonnull urlString) {
        if (urlString && urlString.length) {
            self.headerUrl = urlString;
            self.headerView.headerUrl = urlString;
        }
    }];
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HNSH_AccountCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_AccountCellID];
    cell.dict = self.infoAry[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.infoAry[indexPath.row];
    if ([dic[@"title"] isEqualToString:@"昵称"]) {
        HNSH_ChangeNameViewController *vc = [[HNSH_ChangeNameViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([dic[@"title"] isEqualToString:@"实名认证"]) {
//        HNSH_RealNameAuthViewController *vc = [[HNSH_RealNameAuthViewController alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
    } else if ([dic[@"title"] isEqualToString:@"我的区域"]) {
        if ([ST_UserManager shareInstance].user.location_status == 0) {
            HNSH_UploadLocalAlert *alert = [[HNSH_UploadLocalAlert alloc]initWithFrame:CGRectMake(0, 0, 300, 204)];
            WeakSelf(weakSelf);
            alert.dismissBlock = ^{
                [weakSelf reloadInfoAry];
            };
            [alert showView];
        } else {
            [self.view makeToast:@"修改次数已达上限"];
        }
    }
}

- (void)reloadInfoAry {
    self.infoAry = @[@{@"title":@"昵称",@"des":@""},
                     @{@"title":@"实名认证",@"des":@""},
                     @{@"title":@"我的区域",@"des":[ST_UserManager shareInstance].user.location}
    ];
    [self.tableView reloadData];
}

@end
